<template>
  <div class="manage">
    <el-dialog
      :title="operateType === 'add' ? '新增事务' : '更新事务'"
      :visible.sync="isShow"
    >
      <common-form
        :formLabel="operateFormLabel"
        :form="operateForm"
        ref="form"
      ></common-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="已到期且未完成的事务" :visible.sync="isWaring">
      <el-table
        :data="tableWaringData"
        height="500px"
        stripe
        v-loading="config.loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column label="序号" width="85">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              (config.page - 1) * 20 + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          v-for="item in tableLabel"
          :key="item.prop"
          :label="item.label"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pager"
        layout="prev, pager, next"
        :total="config.total"
        :current-page.sync="config.page"
        :page-size="20"
        @current-change="changePage"
      ></el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isWaring = false">确定</el-button>
        <el-button
          style="margin: 0 10px 10px 10px; float: right"
          @click="handleBatchDelete"
          >批量删除</el-button
        >
      </div>
    </el-dialog>
    <el-dialog title="已完成的事务" :visible.sync="isShowCom">
      <el-table
        :data="tableCompletedData"
        height="500px"
        stripe
        v-loading="config.loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column label="序号" width="85">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{
              (config.page - 1) * 20 + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          v-for="item in tableLabel"
          :key="item.prop"
          :label="item.label"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pager"
        layout="prev, pager, next"
        :total="config.total"
        :current-page.sync="config.page"
        :page-size="20"
        @current-change="changePage"
      ></el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="margin: 0 10px 10px 10px; float: right"
          @click="handleBatchDelete"
          >批量删除</el-button
        >
        <el-button @click="isShowCom = false">确定</el-button>
      </div>
    </el-dialog>
    <div class="manage-header">
      <el-button type="primary" @click="addActivity">+ 新增</el-button>
      <el-button type="warning" @click="openwaring">查看过期未完成的</el-button>
      <el-button type="success" @click="opencompleted">查看已完成的</el-button>
      <el-button @click="sortListByTitle">按标题从A到Z排序</el-button>
      <el-button @click="sortListByContext">按内容从A到Z排序</el-button>
      <el-button @click="sortListByDeadline">按截止从近到远日期</el-button>
      <CommonForm inline :formLabel="formLabel" :form="searchFrom">
        <el-button type="primary" @click="getList(searchFrom.keyword)"
          >搜索</el-button
        >
      </CommonForm>
    </div>
    <common-table
      :tableData="tableData"
      :tableLabel="tableLabel"
      :config="config"
      @changePage="getList"
      @edit="editActivity"
      @delete="delActivity"
    >
    </common-table>
  </div>
</template>

<script>
import CommonForm from "../../components/CommonForm";
import CommonTable from "../../components/CommonTable";
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};
export default {
  components: {
    CommonForm,
    CommonTable,
  },
  data() {
    return {
      tableData: [],
      tableWaringData: [],
      tableCompletedData: [],
      tableLabel: [
        {
          prop: "title",
          label: "标题",
        },
        {
          prop: "activityContext",
          label: "内容",
        },
        {
          prop: "deadline",
          label: "截止日期",
          width: 200,
        },
        {
          prop: "status",
          label: "时间状态",
        },
        {
          prop: "completedLabel",
          label: "完成状态",
        },
        {
          prop: "typeLabel",
          label: "类型",
        },
      ],
      config: {
        page: 1,
        total: 30,
        loading: false,
      },
      operateType: "add",
      isShow: false,
      isWaring: true,
      isShowCom: false,
      isSorted1: false,
      isSorted2: false,
      isSorted3: false,
      operateForm: {
        title: "",
        activityContext: "",
        deadline: "",
      },
      operateFormLabel: [
        {
          model: "title",
          label: "标题",
        },
        {
          model: "activityContext",
          label: "内容",
        },
        {
          model: "deadline",
          label: "截止日期",
          type: "date",
        },
        {
          model: "completed",
          label: "完成状态",
          type: "select",
          opts: [
            {
              label: "未完成",
              value: 0,
            },
            {
              label: "已完成",
              value: 1,
            },
          ],
        },
        {
          model: "type",
          label: "类型",
          type: "select",
          opts: [
            {
              label: "通知",
              value: 0,
            },
            {
              label: "缴费",
              value: 1,
            },
            {
              label: "开会",
              value: 2,
            },
            {
              label: "申请",
              value: 3,
            },
            {
              label: "外出",
              value: 4,
            },
          ],
        },
      ],
      searchFrom: {
        keyword: "",
      },
      formLabel: [
        {
          model: "keyword",
          label: "",
        },
      ],
      typeOptions: [
        {
          label: "通知",
          value: 0,
        },
        {
          label: "缴费",
          value: 1,
        },
        {
          label: "开会",
          value: 2,
        },
        {
          label: "申请",
          value: 3,
        },
        {
          label: "外出",
          value: 4,
        },
      ],
    };
  },
  methods: {
    getList(title = "") {
      console.log(title);
      this.config.loading = true;
      // title ? (this.config.page = 1) : "";
      // title = "";
      console.log(typeof(title))
      if(typeof(title) == "number"){
        title = ""
      }
      this.$http
        .get("/api/activity/getActivity", {
          params: {
            title,
            page: this.config.page,
          },
        })
        .then((res) => {
          this.tableData = res.data.list.map((item) => {
            // 随机模拟数据时日期范围大，为了测试过期事务的甄别功能设置
            let d1 = new Date(2000, 1, 1).format("yyyy-MM-dd");
            // let d1 = new Date().format("yyyy-mm-dd");
            item.completedLabel = item.completed === 0 ? "未完成" : "已完成";
            for (let index1 = 0; index1 < this.typeOptions.length; index1++) {
              if (item.type == this.typeOptions[index1].value) {
                item.typeLabel = this.typeOptions[index1].label;
              }
            }
            if (d1.valueOf() < item.deadline.valueOf()) {
              item.status = "未过期";
              return item;
            } else if (d1.valueOf() == item.deadline.valueOf()) {
              item.status = "即将过期";
              return item;
            } else {
              item.status = "已过期";
              if (item.completedLabel == "未完成") {
                this.tableWaringData.push(item);
              }
              return item;
            }
          });
          this.config.total = res.data.count;
          this.config.loading = false;
        });
    },
    getCompletedList() {
      let temp = [];
      for (let index = 0; index < this.tableData.length; index++) {
        if (this.tableData[index].completedLabel == "已完成") {
          temp.push(this.tableData[index]);
        }
      }
      this.tableCompletedData = temp;
    },
    getWaringList() {
      let temp = [];
      for (let index = 0; index < this.tableData.length; index++) {
        if (
          this.tableData[index].completedLabel == "未完成" &&
          this.tableData[index].status == "已过期"
        ) {
          temp.push(this.tableData[index]);
        }
      }
      this.tableWaringData = temp;
    },
    addActivity() {
      console.log("addActivity");
      this.operateType = "add";
      this.isShow = true;
    },
    editActivity(row) {
      this.operateType = "edit";
      this.isShow = true;
      this.operateForm = row;
    },
    delActivity(row) {
      console.log(row);
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = row.id;
          this.$http
            .get("/api/activity/del", {
              params: {
                id,
              },
            })
            .then((res) => {
              console.log(res.data);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            });
          console.log("提交给后台进行删除");
          this.getList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    confirm() {
      if(this.operateForm.title.trim().length <= 0){
        return this.$message.warning("标题不能为空");
      }
      if (this.operateForm.activityContext.trim().length <= 0) {
        return this.$message.warning("内容不能为空");
      }
      if (this.operateType === "edit") {
        this.$http.post("/api/activity/edit", this.operateForm).then((res) => {
          console.log(res.data);
          this.isShow = false;
          this.getList();
        });
      } else {
        this.$http.post("/api/activity/add", this.operateForm).then((res) => {
          console.log(res.data);
          this.isShow = false;
          this.getList();
        });
      }
      this.getList();
    },
    changePage(page) {
      this.config.page = page;
    },
    openwaring() {
      this.getWaringList();
      this.isWaring = true;
    },
    opencompleted() {
      this.getCompletedList();
      this.isShowCom = true;
    },
    formatDate(value) {
      var date = new Date(value).format("yyyy-MM-dd");
      return date;
    },
    sortList(lists, greName) {
      return lists.sort((a, b) => {
        return a[greName].localeCompare(b[greName]);
      });
    },
    sortListByTitle() {
      if (!this.isSorted1) {
        this.tableData = this.sortList(this.tableData, "title");
        this.isSorted1 = true;
      } else {
        this.tableData = this.getList();
        this.isSorted1 = false;
      }
    },
    sortListByContext() {
      if (!this.isSorted2) {
        this.tableData = this.sortList(this.tableData, "activityContext");
        this.isSorted2 = true;
      } else {
        this.tableData = this.getList();
        this.isSorted2 = false;
      }
    },
    sortListByDeadline() {
      if (!this.isSorted3) {
        this.tableData = this.sortList(this.tableData, "deadline").reverse();
        this.isSorted3 = true;
      } else {
        this.tableData = this.getList();
        this.isSorted3 = false;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleBatchDelete() {
      console.log(this.multipleSelection, "multipleSelection");
      if (this.multipleSelection.length <= 0) {
        this.$message({
          type: "warning",
          message: "请至少勾选一条数据",
          showClose: true,
        });
        return;
      }
      var ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.$confirm("此操作将永久批量删除记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(ids, "请求内");
          this.$http
            .post("/api/activity/batchremove", {
              ids,
            })
            .then((res) => {
              console.log(res.data);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
              this.getCompletedList();
              this.getWaringList();
            });
          console.log("提交给后台进行删除");
          this.getList();
          this.getCompletedList();
          this.getWaringList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/common";
</style>